<?php
class Application{
	public $err = null;
	public $controller = null;
	public $modules = array();
	public $available_modules = array(
		'builder' => 'SqlBuilder',
		'db' => 'DbModule',
		'session' => 'Session',
		'request' => 'RequestManager',
		'parser' => 'TemplateParser'
	);
	public $excluded_modules = array();
	
	public $template_css_class = array();
	public $template_css_class_i = 1;
	
	public function Application($err_manager, $request){
		$this->err = $err_manager;
		$this->load_modules();
		$this->load_controller($this->request->get_mapping());
		$this->err->flush();
	}
	
	public function load_controller($mapping){
		if(!$mapping){
			$this->err->fatal_error('A problem occured trying to identify your request');
		}
		if(!$mapping['controller']){
			$this->err->fatal_error('No controller specified by load map.');
		}
		$controller_name = ucfirst($mapping['controller']).'Controller';
		if(!$mapping['method']){
			$this->err->fatal_error('No method specified by load map for the <strong>'.$controller_name.'</strong>.');
		}
		$file = APP_FULL_DIR.'controllers/'.$mapping['controller'].'.php';
		if(!file_exists($file)){
			$this->err->fatal_error('Controller <strong>'.$controller_name.'</strong> does not exist. Please create <strong>controllers/'.$mapping['controller'].'.php</strong>.');
		}
		require_once(APP_FULL_DIR.'controllers/app.php');
		require_once($file);
		$this->controller = new $controller_name();
		$this->controller->app = $this;
		$this->controller->err = $this->err;
		$this->controller->init($this->modules, $mapping);
	}
	
	private function load_modules(){
		foreach($this->available_modules as $module => $name){
			if(!in_array($module, $this->excluded_modules)){
				$this->load_module($module);
			}
		}
	}
	
	private function load_module($name){
		if(in_array($name, $this->modules)){
			$this->err->dump_warning('Module <strong>'.$this->available_modules['name'].'</strong> has already been loaded.');
		}else{
			$file = CORE_PATH.'modules/'.$this->available_modules[$name].'.php';
			if(!file_exists($file)){
				$this->err->fatal_error('Module <strong>'.$this->available_modules[$name].'</strong> is not available.<br/>Please create <strong>'.$file.'</strong>');
			}
			$this->modules[] = $name;
			require_once($file);
			$this->$name = new $this->available_modules[$name]($this);
		}
	}
	
	public function module_loaded($name){
		return in_array($name, $this->modules);
	}
}
?>